import { Runtime } from "./Runtime";

const wx = window['wx'];

export class Weh5Runtime extends Runtime {
    // wxPay = (payParams, callback: () => void) => {
    //     const that = this;
    //     wx.chooseWXPay({
    //         timeStamp: payParams.timeStamp,
    //         nonceStr: payParams.nonceStr,
    //         package: payParams.package,
    //         signType: payParams.signType,
    //         paySign: payParams.paySign,
    //         success(res) {
    //             console.log(res);
    //             callback();
    //         },
    //         fail(res) {
    //             console.log(res);
    //             that.showToast("支付失败");
    //         }
    //     });
    // }
    
    wxPay = (payParams, callback: () => void) => {
        // alert(JSON.stringify(payParams));
        if (typeof window['WeixinJSBridge'] == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady',
                    () => this.onBridgeReady(payParams, callback), false);
            } else if (document['attachEvent']) {
                document['attachEvent']('WeixinJSBridgeReady',
                    () => this.onBridgeReady(payParams, callback));
                document['attachEvent']('onWeixinJSBridgeReady',
                    () => this.onBridgeReady(payParams, callback));
            }
        } else {
            this.onBridgeReady(payParams, callback);
        }
    }

    /**
     *  微信支付
     */
    onBridgeReady = (payParams, callback: () => void) => {
        const that = this;
        window['WeixinJSBridge'].invoke(
            'getBrandWCPayRequest',
            payParams,
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    callback();
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    that.showToast("支付取消");
                } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                    that.showToast('支付失败');
                }
            }
        );
    }
}
